<?php
namespace backend\controllers\rbac;
Use common\models\RbacRole;
use backend\controllers\BackendBase;
use yii\helpers\Json;

class RoleController extends BackendBase
{
    public function actionIndex(){
        if(!$this->isJson){
            return $this->renderView('/rbac/role/index');
        }
        return $this->page( RbacRole::find() ) ;
    }


    public function actionSave(){
        $id = $this->request()->get('id',0);
        if(!$this->isPost){

            $data = '""' ;
            if($id){
                $data = RbacRole::find()->where(['id' => $id])->with('res')->asArray()->one() ;
                $data['res'] = array_map(function($item){
                    return $item['resource_id'] ;
                },$data['res']) ;
                $data = Json::encode($data) ;
            }

            return $this->renderView('/rbac/role/save',['data' => $data]);
        }

        $data = $this->request()->post() ;

        if($id){
            $model = RbacRole::findOne($id);
        }else{
            $model = new RbacRole();
        }


        if($model->load($data,'') && $model->save()){
            $model->saveRes($data['res']) ;
            return true ;
        }else{
            return $model->getErrors() ;
        }
    }


    public function actionDelete(){
        $id = $this->request()->get('id',0);
        $isDelete = RbacRole::findOne($id)->delete();
        return ['code' => 0];
    }
}